<?php

require_once 'Pipes/Controller.php';
require_once 'Pipes/Model/Mapper/Factory.php';
require_once 'Pipes/Route/Simple.php';
require_once 'PipesImpl/Model/Mapper.php';

class Pipes_Controller_Model extends Pipes_Controller
{
	protected $_model = null;
	protected $_modelList = null;
	protected $_modelMapper = null;
	
	public function __construct(PipesImpl_Config $config) {
		parent::__construct($config);
		
		$factory = new Pipes_Model_Mapper_Factory($this->_config);
		$this->_modelMapper = $factory->factory($this->getName());
	}
	
	protected function actionAdd() {
		$this->actionEdit(null);
	}
	
	protected function actionEdit($id) {
		$this->_view->model = $this->_modelMapper->find($id);
	}
	
	protected function actionView($id) {
		$this->_view->model = $this->_modelMapper->find($id);
	}
	
	protected function actionBrowse($type = null, $extra = null) {
		switch ($type) {
			case 'tag' :
				$this->_modelList = $this->_modelMapper->findByTags(explode(',', $extra));
				break;

			default:
				$this->_modelList = $this->_modelMapper->findAll();
		}

		$this->_view->modelList = $this->_modelList;
	}

	protected function actionDashboard() {
		$subController = clone $this;
		$route = new Pipes_Route_Simple($this->getName(), 'browse', array('isAjax' => 1));
		$this->_view->browse = $subController->run($route, $this->_currentCredentials);
	}

	protected function actionRemove($id) {
		$model = $this->_modelMapper->find($id);
		$this->_modelMapper->remove($model);

		$this->_view->model = $model;
	}
	
	protected function dispatch(PipesImpl_Route $route) {
		$name = strtolower($this->getName());
		if (isset($_POST['pipes']['action'][$name])) {
			if (isset($_POST[$name]["{$name}_id"])) {
				$this->_model = $this->_modelMapper->find($_POST[$name]["{$name}_id"]);
				unset($_POST[$name]["{$name}_id"]);
			} else {
				$this->_model = $this->_modelMapper->find();
			}
			foreach ($_POST[$name] as $key => $value) {
				$this->_model->$key = $value;
			}
			
			$action = strtolower($_POST['pipes']['action'][$name]);
			$this->_model->$action();
		}

		parent::dispatch($route);
	}
}

